package com.yunquan.ohana.ui.weather.search

import androidx.databinding.ObservableField
import androidx.lifecycle.viewModelScope
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.ui.ItemViewModel
import com.yunquan.ohana.db.DBWeatherLocation
import com.yunquan.ohana.entity.LocalLocationModel
import com.yunquan.ohana.entity.Location
import com.yunquan.ohana.entity.UserManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class WeatherSearchHistoryItemViewModel(viewModel: WeatherSearchViewModel) : ItemViewModel<WeatherSearchViewModel>(viewModel) {

    var data: LocalLocationModel? = null

    val name = ObservableField<String>()

    constructor(viewModel: WeatherSearchViewModel, data: LocalLocationModel) : this(viewModel) {
        this.data = data
        this.name.set(data.name)
    }

    val onItemClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            viewModel.viewModelScope.launch(Dispatchers.IO) {
                var bean = DBWeatherLocation.instance.selectOne(
                    "user_id = ? AND name = ?",
                    arrayOf(UserManager.instance.getUser()?.id.toString(), data!!.name!!)
                )
                withContext(Dispatchers.Main) {
                    if (bean == null) {
                        viewModel.searchCity(data!!.name!!)
                    } else {
                        val cityBean = Location(
                            id = data!!.locationId,
                            name = data!!.name,
                            lat = data!!.latitude,
                            lon = data!!.longitude,
                            tz = data?.timeZone,
                            utcOffset = data?.utcOffset
                        )
                        viewModel.changeCity.value = cityBean
                    }
                }
            }
        }
    })

    val onDeleteClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            viewModel.viewModelScope.launch(Dispatchers.IO) {
                if (data?.id != null) {
                    DBWeatherLocation.instance.delete(data!!.id!!)
                }
                withContext(Dispatchers.Main){
                    viewModel.localData()
                }
            }
        }
    })
}